package com.projx.accounting.service;

import com.projx.accounting.module.Bill;
import com.projx.accounting.repository.BillRepository;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Optional;

@Service
public class BillService {
    private final BillRepository repo;

    public BillService(BillRepository repo) {
        this.repo = repo;
    }

    public Bill create(Bill bill) {
        return repo.save(bill);
    }

    public Optional<Bill> findById(String id) {
        return repo.findById(id);
    }

    public List<Bill> listAll() {
        return repo.findAll();
    }

    public List<Bill> listByOwner(String ownerId) {
        return repo.findByOwnerId(ownerId);
    }

    public double sumByOwnerBetween(String ownerId, java.time.OffsetDateTime from, java.time.OffsetDateTime to) {
        return repo.findByOwnerId(ownerId).stream()
                .filter(b -> b.getCreatedAt() != null &&
                        (from == null || !b.getCreatedAt().isBefore(from)) &&
                        (to == null || !b.getCreatedAt().isAfter(to)))
                .mapToDouble(b -> {
                    double amt = b.getAmount() == null ? 0.0 : b.getAmount();
                    if ("EXPENSE".equalsIgnoreCase(b.getType())) return -Math.abs(amt);
                    return Math.abs(amt);
                })
                .sum();
    }

    public Bill update(Bill bill) {
        if (bill.getId() == null) throw new IllegalArgumentException("id required for update");
        return repo.save(bill);
    }

    public boolean delete(String id) {
        if (!repo.existsById(id)) return false;
        repo.deleteById(id);
        return true;
    }
}
